package com.hl.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hl.Util.*;
import com.hl.entity.*;
import com.hl.entity.Class;
import com.hl.service.ClassService;
import com.hl.service.QuestionService;
import com.hl.service.impl.*;
import com.hl.vo.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.ibatis.reflection.ArrayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Date 2022-1-18 09:50:02
 * @created by hl
 */
@RestController
@RequestMapping(value = "/teacher")
@Slf4j
public class TeacherController {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private QuestionBankServiceImpl questionBankService;

    @Autowired
    private QuestionServiceImpl questionService;

    @Autowired
    private AnswerServiceImpl answerService;

    @Autowired
    private ExamServiceImpl examService;

    @Autowired
    private ExamQuestionServiceImpl examQuestionService;

    @Autowired
    private ClassServiceImpl classService;

    @Autowired
    private UserClassRelServiceImpl userClassRelService;

    @Autowired
    private ExamRecordServiceImpl examRecordService;

    //注入自己的redis工具类
    @Autowired
    private RedisUtil redisUtil;

    //jackson
    ObjectMapper mapper = new ObjectMapper();

    @GetMapping("/getQuestionBank")
    @ApiOperation("获取所有题库信息")
    public CommonResult<Object> getQuestionBank(HttpServletRequest request) {
        log.info("执行了===>TeacherController中的getQuestionBank方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            QueryWrapper<QuestionBank> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            String userName = tokenVo.getUsername();
            if (roleId.equals("2")) {
                wrapper.eq("creator", userName);
            }
            List<QuestionBank> questionBanks = questionBankService.list(wrapper);
            return new CommonResult<>(200, "success", questionBanks);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param bankName 题目名称
     * @param pageNo   页面数
     * @param pageSize 页面大小
     * @return
     */
    @GetMapping("/getBankHaveQuestionSumByType")
    public CommonResult<Object> getBankHaveQuestionSumByType(@RequestParam(required = false) String bankName,
                                                             Integer pageNo, Integer pageSize, HttpServletRequest request) {
        log.info("执行了===>TeacherController中的getBankHaveQuestionSumByType方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            //参数一是当前页，参数二是每页个数
            IPage<QuestionBank> questionBankIPage = new Page<>(pageNo, pageSize);
            //查询条件(可选)
            QueryWrapper<QuestionBank> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            String userName = tokenVo.getUsername();
            if (!Objects.equals(bankName, "") && bankName != null) {
                wrapper.like("bank_name", bankName);
            }
            if (roleId.equals("2")) {
                wrapper.eq("creator", userName);
            }
            IPage<QuestionBank> iPage = questionBankService.page(questionBankIPage, wrapper);
            List<QuestionBank> questionBanks = iPage.getRecords();

            //封装成传给前端的数据类型
            List<BankHaveQuestionSum> bankHaveQuestionSums = new ArrayList<>();
            for (QuestionBank questionBank : questionBanks) {
                //创建vo对象
                BankHaveQuestionSum bankHaveQuestionSum = new BankHaveQuestionSum();
                //设置属性
                bankHaveQuestionSum.setQuestionBank(questionBank);
                //设置单选题的数量
                List<Question> singleQuestions = questionService.list(new QueryWrapper<Question>().eq("qu_type", 1).apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
                bankHaveQuestionSum.setSingleChoice(singleQuestions.size());
                //设置多选题的数量
                List<Question> multipleQuestions = questionService.list(new QueryWrapper<Question>().eq("qu_type", 2).apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
                bankHaveQuestionSum.setMultipleChoice(multipleQuestions.size());
                //设置判断题的数量
                List<Question> judgeQuestions = questionService.list(new QueryWrapper<Question>().eq("qu_type", 3).apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
                bankHaveQuestionSum.setJudge(judgeQuestions.size());
                //设置简答题的数量
                List<Question> shortAnswerQuestions = questionService.list(new QueryWrapper<Question>().eq("qu_type", 4).apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
                bankHaveQuestionSum.setShortAnswer(shortAnswerQuestions.size());
                //设置填空题的数量
                List<Question> completionQuestions = questionService.list(new QueryWrapper<Question>().eq("qu_type", 5).apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
                bankHaveQuestionSum.setCompletion(completionQuestions.size());
                //加入list中
                bankHaveQuestionSums.add(bankHaveQuestionSum);
            }
            // 创建分页结果集
            Map<Object, Object> result = new HashMap<>();
            result.put("bankHaveQuestionSums", bankHaveQuestionSums);
            result.put("total", iPage.getTotal());
            return new CommonResult<>(200, "查询题库和所属题目信息成功", result);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }

    }

    /**
     * @param questionBank
     * @return
     */
    @PostMapping("/addQuestionBank")
    public CommonResult<String> addQuestionBank(@RequestBody QuestionBank questionBank, HttpServletRequest request) {
        log.info("执行了===>TeacherController中的addQuestionBank方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            String userName = tokenVo.getUsername();
            questionBank.setCreator(userName);
            questionBank.setCreateDate(new Date());
            boolean flag = questionBankService.save(questionBank);
            return flag ? new CommonResult<>(200, "添加题库成功") : new CommonResult<>(200, "添加题库失败");
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param ids
     * @return
     */
    @GetMapping("/deleteQuestionBank")
    public CommonResult<String> deleteQuestionBank(String ids) {
        log.info("执行了===>TeacherController中的deleteQuestionBank方法");
        String[] bankId = ids.split(",");
        for (String s : bankId) {
            //找到题库
            QuestionBank questionBank = questionBankService.getById(s);
            //找到与此题库相关的所有问题信息
            List<Question> questions = questionService.list(new QueryWrapper<Question>().apply("FIND_IN_SET ('" + questionBank.getBankId() + "',qu_bank_id)"));
            //移除与此题库相关的信息
            for (Question question : questions) {
                String quBankName = question.getQuBankName();
                String quBankId = question.getQuBankId();
                String[] name = quBankName.split(",");
                String[] id = quBankId.split(",");
                //新的题库名
                String[] newName = new String[name.length - 1];
                //新的题库id数据
                String[] newId = new String[id.length - 1];

                for (int i = 0, j = 0; i < name.length; i++) {
                    if (!name[i].equals(questionBank.getBankName())) {
                        newName[j] = name[i];
                        j++;
                    }
                }
                for (int i = 0, j = 0; i < id.length; i++) {
                    if (!id[i].equals(String.valueOf(questionBank.getBankId()))) {
                        newId[j] = id[i];
                        j++;
                    }
                }
                String handleName = Arrays.toString(newName)
                        .replaceAll(" ", "")
                        .replaceAll("]", "")
                        .replace("[", "");
                String handleId = Arrays.toString(newId).replaceAll(" ", "")
                        .replaceAll("]", "")
                        .replace("[", "");
                //设置删除题库后的新字段
                question.setQuBankName(handleName);
                question.setQuBankId(handleId);
                //更新题目
                questionService.update(question, new UpdateWrapper<Question>().eq("id", question.getId()));
            }
            //删除题库
            questionBankService.removeById(Integer.parseInt(s));
            //清除题库的缓存
            redisUtil.del("questionBanks");
        }
        return new CommonResult<>(200, "删除题库成功");
    }

    /**
     * @param questionType    问题类型
     * @param questionBank    问题所属题库
     * @param questionContent 问题内容
     * @param pageNo          页面数
     * @param pageSize        页面大小
     * @return
     */
    @GetMapping("/getQuestion")
    public CommonResult<Object> getQuestion(@RequestParam(required = false) String questionType,
                                            @RequestParam(required = false) String questionBank,
                                            @RequestParam(required = false) String questionContent,
                                            HttpServletRequest request,
                                            Integer pageNo, Integer pageSize) {
        log.info("执行了===>TeacherController中的getQuestion方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            String userName = tokenVo.getUsername();
            String roleId = tokenVo.getRoleId();
            //参数一是当前页，参数二是每页个数
            IPage<Question> questionPage = new Page<>(pageNo, pageSize);
            //查询条件(可选)
            QueryWrapper<Question> wrapper = new QueryWrapper<>();
            if (roleId.equals("2")) {
                wrapper.eq("create_person", userName);
            }
            if (!Objects.equals(questionType, "")) {
                wrapper.eq("qu_type", questionType);
            }
            if (!Objects.equals(questionBank, "")) {
                wrapper.like("qu_bank_name", questionBank);
            }
            if (!Objects.equals(questionContent, "")) {
                wrapper.like("qu_content", questionContent);
            }

            questionPage = questionService.page(questionPage, wrapper);
            List<Question> questions = questionPage.getRecords();
            // 创建分页结果集
            Map<Object, Object> result = new HashMap<>();
            result.put("questions", questions);
            result.put("total", questionPage.getTotal());
            return new CommonResult<>(200, "success", result);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param questionType    问题类型
     * @param questionBank    问题所属题库
     * @param singleChoice    单选题数量
     * @param multipleChoice  多选题数量
     * @param judge           判断题数量
     * @param completion      填空题数量
     * @param shortAnswer     简答题数量
     * @return
     */
    @GetMapping("/getQuRandom")
    public CommonResult<Object> getQuRandom(@RequestParam(required = true) String questionType,
                                            @RequestParam(required = true) String questionBank,
                                            @RequestParam(required = true) String singleChoice,
                                            @RequestParam(required = true) String multipleChoice,
                                            @RequestParam(required = true) String judge,
                                            @RequestParam(required = true) String completion,
                                            @RequestParam(required = true) String shortAnswer ){
        log.info("执行了===>TeacherController中的getQuRandom方法");
        String[] quTypes = questionType.split(",");
        List<String> quBanks = Arrays.asList(questionBank.split(","));
        List<Question> questions = new ArrayList<>();
        for(String quType : quTypes){
            QueryWrapper<Question> quWrapper = new QueryWrapper<>();
            quWrapper.eq("qu_type",quType);
            quWrapper.and(w->{
                quBanks.forEach(i->w.or().apply(!i.isEmpty(),"FIND_IN_SET ('" + i + "',qu_bank_id)"));
                        return w;
                    }
            );
            quWrapper.orderByDesc("rand()");
            if(quType.equals("1")){
                quWrapper.last("limit "+singleChoice);
            }else if(quType.equals("2")){
                quWrapper.last("limit "+multipleChoice);
            }else if(quType.equals("3")){
                quWrapper.last("limit "+judge);
            }else if(quType.equals("4")){
                quWrapper.last("limit "+shortAnswer);
            }else if(quType.equals("5")){
                quWrapper.last("limit "+completion);
            }else{
                return new CommonResult<>(233, "认证信息有误,获取数据失败");
            }
            questions.addAll(questionService.list(quWrapper));
        }
        if(questions!=null&&!questions.isEmpty()){
            Map<Object, Object> result = new HashMap<>();
            result.put("questions", questions);
            return new CommonResult<>(200, "success",result);
        }
        return new CommonResult<>(233, "认证信息有误,获取数据失败");
    }

    /**
     * @param questionIds 需要删除的问题id的字符串,逗号分隔
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/deleteQuestion")
    @Transactional
    public CommonResult<String> deleteQuestion(String questionIds) throws InterruptedException {
        log.info("执行了===>TeacherController中的deleteQuestion方法");
        String[] ids = questionIds.split(",");
        Map<String, Object> map = new HashMap<>();
        for (String id : ids) {
            map.clear();
            map.put("question_id", id);
            // 1. 删除数据库的题目信息
            questionService.removeById(Integer.parseInt(id));
            //2. 删除答案表对应当前题目id的答案
            answerService.removeByMap(map);
            // 2. 移除redis缓存
            redisUtil.del("questionVo:" + id);
        }
        // 清楚题库的缓存
        redisUtil.del("questionBanks");
        return new CommonResult<>(200, "删除成功");
    }

    /**
     * @param questionIds 问题id字符串,逗号分隔
     * @param banks       题库id字符串,逗号分隔
     * @return
     */
    @GetMapping("/addBankQuestion")
    public CommonResult<String> addBankQuestion(String questionIds, String banks) {
        log.info("执行了===>TeacherController中的addBankQuestion方法");
        boolean flag = false;
        //需要操作的问题
        String[] quIds = questionIds.split(",");
        //需要放入的题库id
        String[] bankIds = banks.split(",");

        //将每一个题目放入每一个题库中
        for (String quId : quIds) {
            //当前的问题对象
            Question question = questionService.getById(Integer.parseInt(quId));
            String quBankId = question.getQuBankId();
            //当前已经有的题库id
            String[] qid = quBankId.split(",");
            System.out.println(quBankId);
            //存在去重后的题库id
            Set<Integer> allId = new HashSet<>();
            if (!quBankId.equals("")) {//防止题目没有题库
                for (String s : qid) {
                    allId.add(Integer.parseInt(s));
                }
            }
            //将新增的仓库id放入
            for (String bankId : bankIds) {
                allId.add(Integer.parseInt(bankId));
            }
            //处理后的id字符串 例如(1,2,3)
            String handleHaveBankIds = allId.toString().replaceAll(" ", "");
            handleHaveBankIds = handleHaveBankIds.substring(1, handleHaveBankIds.length() - 1);
            //更新当前用户的题库id值
            question.setQuBankId(handleHaveBankIds);

            //将存放处理后的set集合遍历,然后替换数据库的题库名
            StringBuilder bankNames = new StringBuilder();
            for (Integer id : allId) {
                bankNames.append(questionBankService.getById(id).getBankName()).append(",");
            }
            //替换原来的仓库名称
            question.setQuBankName(bankNames.toString().substring(0, bankNames.toString().length() - 1));
            //更新问题对象
            flag = questionService.update(question, new UpdateWrapper<Question>().eq("id", question.getId()));
        }
        return flag ? new CommonResult<>(200, "添加题库成功") : new CommonResult<>(233, "添加题库失败");
    }

    /**
     * @param questionIds 问题id字符串,逗号分隔
     * @param banks       题库id字符串,逗号分隔
     * @return
     */
    @GetMapping("/removeBankQuestion")
    @Transactional
    public CommonResult<String> removeBankQuestion(String questionIds, String banks) {
        log.info("执行了===>TeacherController中的removeBankQuestion方法");
        boolean flag = false;
        //需要操作的问题
        String[] quIds = questionIds.split(",");
        //需要移除的题库id
        String[] bankIds = banks.split(",");
        //操作需要移除仓库的问题
        for (String quId : quIds) {
            Question question = questionService.getById(Integer.parseInt(quId));
            String quBankId = question.getQuBankId();
            //当前问题拥有的仓库id
            String[] curHaveId = quBankId.split(",");
            //存储处理后的id
            Set<Integer> handleId = new HashSet<>();
            if (!quBankId.equals("")) {
                for (String s : curHaveId) {
                    handleId.add(Integer.parseInt(s));
                }
            }
            //遍历查询set中是否含有需要删除的仓库id
            for (String bankId : bankIds) {
                handleId.remove(Integer.parseInt(bankId));
            }
            //处理后的id字符串 例如(1,2,3)
            String handleHaveBankIds = handleId.toString().replaceAll(" ", "");
            handleHaveBankIds = handleHaveBankIds.substring(1, handleHaveBankIds.length() - 1);
            //更新当前用户的题库id值
            question.setQuBankId(handleHaveBankIds);

            if (!handleHaveBankIds.equals("")) {//删除后还存在剩余的题库
                //将存放处理后的set集合遍历,然后替换数据库的题库名
                StringBuilder bankNames = new StringBuilder();
                for (Integer id : handleId) {
                    bankNames.append(questionBankService.getById(id).getBankName()).append(",");
                }
                //替换原来的仓库名称
                question.setQuBankName(bankNames.toString().substring(0, bankNames.toString().length() - 1));
            } else {//不剩题库了
                question.setQuBankName("");
            }
            //更新问题对象
            flag = questionService.update(question, new UpdateWrapper<Question>().eq("id", question.getId()));
        }
        return flag ? new CommonResult<>(200, "移除题库成功") : new CommonResult<>(233, "移除题库失败");
    }

    /**
     * @param questionVo 试题Vo对象
     * @return
     */
    @PostMapping("/addQuestion")
    public CommonResult<String> addQuestion(@RequestBody QuestionVo questionVo) {
        log.info("执行了===>TeacherController中的addQuestion方法");
        //查询所有的问题,然后就可以设置当前问题的id了
        List<Question> qus = questionService.list(new QueryWrapper<>());
        Integer currentQuId;
        if (qus.size() == 0) {
            currentQuId = 1;
        } else {
            currentQuId = qus.get(qus.size() - 1).getId() + 1;
        }
        Question question = new Question();
        //设置基础字段
        question.setQuType(questionVo.getQuestionType());
        question.setId(currentQuId);
        question.setCreateTime(new Date());
        question.setLevel(questionVo.getQuestionLevel());
        question.setAnalysis(questionVo.getAnalysis());
        question.setQuContent(questionVo.getQuestionContent());
        question.setCreatePerson(questionVo.getCreatePerson());
        //设置所属题库
        String bankIds = Arrays.toString(questionVo.getBankId());
        question.setQuBankId(bankIds.substring(1, bankIds.length() - 1).replaceAll(" ", ""));
        //设置题目插图
        if (questionVo.getImages().length != 0) {
            String QuImages = Arrays.toString(questionVo.getImages());
            question.setImage(QuImages.substring(1, QuImages.length() - 1).replaceAll(" ", ""));
        }
        StringBuilder bankNames = new StringBuilder();
        for (Integer integer : questionVo.getBankId()) {
            bankNames.append(questionBankService.getById(integer).getBankName()).append(",");
        }
        String names = bankNames.toString();
        names = names.substring(0, names.length() - 1);
        question.setQuBankName(names);

        questionService.save(question);
        //设置答案对象
        StringBuffer multipleChoice = new StringBuffer();
        if (questionVo.getQuestionType() != 4) {//不为简答题
            Answer answer = new Answer();
            answer.setQuestionId(currentQuId);
            StringBuffer imgs = new StringBuffer();
            StringBuffer answers = new StringBuffer();
            for (int i = 0; i < questionVo.getAnswer().length; i++) {
                if (questionVo.getAnswer()[i].getImages().length > 0) {//如果该选项有一张图片信息
                    imgs.append(questionVo.getAnswer()[i].getImages()[0]).append(",");
                }
                answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                //设置对的选项的下标值
                if (questionVo.getQuestionType() == 2) {//多选
                    if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                        multipleChoice.append(i).append(",");
                    }
                } else {//单选和判断和填空 都是仅有一个答案
                    if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                        answer.setTrueOption(i + "");
                        answer.setAnalysis(questionVo.getAnswer()[i].getAnalysis());
                    }
                }
            }
            if (questionVo.getQuestionType() == 2)
                answer.setTrueOption(multipleChoice.toString().substring(0, multipleChoice.toString().length() - 1));
            String handleImgs = imgs.toString();
            String handleAnswers = answers.toString();
            if (handleImgs.length() != 0) {
                handleImgs = handleImgs.substring(0, handleImgs.length() - 1);
            }
            if (handleAnswers.length() != 0) {
                handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);
            }

            //设置答案的图片
            answer.setImages(handleImgs);
            //设置所有的选项
            answer.setAllOption(handleAnswers);
            answerService.save(answer);
            //清楚题库的缓存
            redisUtil.del("questionBanks");
        }
        return new CommonResult<>(200, "新增题目成功");
    }

    /**
     * @param id 题目id
     * @return
     */
    @GetMapping("/getQuestionById/{id}")
    public CommonResult<Object> getQuestionById(@PathVariable("id") Integer id) {
        log.info("执行了===>TeacherController中的getQuestionById方法");
            Question question = questionService.getById(id);
            Answer answer = answerService.getOne(new QueryWrapper<Answer>().eq("question_id", id));
            QuestionVo questionVo = new QuestionVo();
            //设置字段
            questionVo.setQuestionContent(question.getQuContent());
            questionVo.setAnalysis(question.getAnalysis());
            questionVo.setQuestionType(question.getQuType());
            questionVo.setQuestionLevel(question.getLevel());
            questionVo.setQuestionId(question.getId());
            if (question.getImage() != null && !Objects.equals(question.getImage(), "")) {
                questionVo.setImages(question.getImage().split(","));
            }
            questionVo.setCreatePerson(question.getCreatePerson());
            //设置所属题库
            if (!Objects.equals(question.getQuBankId(), "")) {
                String[] bids = question.getQuBankId().split(",");
                Integer[] bankIds = new Integer[bids.length];
                for (int i = 0; i < bids.length; i++) {
                    bankIds[i] = Integer.parseInt(bids[i]);
                }
                questionVo.setBankId(bankIds);
            }
            if (answer != null) {
                if (question.getQuType() != 2) {
                    String[] allOption = answer.getAllOption().split(",");
                    String[] imgs = answer.getImages().split(",");
                    QuestionVo.Answer[] qa = new QuestionVo.Answer[allOption.length];
                    for (int i = 0; i < allOption.length; i++) {
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setId(i);
                        answer1.setAnswer(allOption[i]);
                        if (i <= imgs.length - 1 && !Objects.equals(imgs[i], "")) {
                            answer1.setImages(new String[]{imgs[i]});
                        }
                        if (i == Integer.parseInt(answer.getTrueOption()) || question.getQuType() == 5) {
                            answer1.setIsTrue("true");
                            answer1.setAnalysis(answer.getAnalysis());
                        }
                        qa[i] = answer1;
                    }
                    questionVo.setAnswer(qa);
                } else {//多选
                    String[] allOption = answer.getAllOption().split(",");
                    String[] imgs = answer.getImages().split(",");
                    QuestionVo.Answer[] qa = new QuestionVo.Answer[allOption.length];
                    for (int i = 0; i < allOption.length; i++) {
                        QuestionVo.Answer answer1 = new QuestionVo.Answer();
                        answer1.setId(i);
                        answer1.setAnswer(allOption[i]);
                        answer1.setImages(imgs);
                        if (i < answer.getTrueOption().split(",").length && i == Integer.parseInt(answer.getTrueOption().split(",")[i])) {
                            answer1.setIsTrue("true");
                            answer1.setAnalysis(answer.getAnalysis());
                        }
                        qa[i] = answer1;
                    }
                    questionVo.setAnswer(qa);
                }
            }
            return new CommonResult<>(200, "查询成功", questionVo);
    }

    /**
     * @param questionVo 问题vo对象
     * @return
     */
    @PostMapping("/updateQuestion")
    public CommonResult<String> updateQuestion(@RequestBody QuestionVo questionVo) {
        log.info("执行了===>TeacherController中的updateQuestion方法");
        Question question = new Question();
        //设置基础字段
        question.setQuType(questionVo.getQuestionType());
        question.setId(questionVo.getQuestionId());
        question.setCreateTime(new Date());
        question.setLevel(questionVo.getQuestionLevel());
        question.setAnalysis(questionVo.getAnalysis());
        question.setQuContent(questionVo.getQuestionContent());
        question.setCreatePerson(questionVo.getCreatePerson());
        //设置所属题库
        String bankIds = Arrays.toString(questionVo.getBankId());
        question.setQuBankId(bankIds.substring(1, bankIds.length() - 1).replaceAll(" ", ""));
        //设置题目插图
        if (questionVo.getImages() != null && questionVo.getImages().length != 0) {
            String QuImages = Arrays.toString(questionVo.getImages());
            question.setImage(QuImages.substring(1, QuImages.length() - 1).replaceAll(" ", ""));
        }
        StringBuilder bankNames = new StringBuilder();
        for (Integer integer : questionVo.getBankId()) {
            bankNames.append(questionBankService.getById(integer).getBankName()).append(",");
        }
        String names = bankNames.toString();
        names = names.substring(0, names.length() - 1);
        question.setQuBankName(names);
        //更新
        questionService.update(question, new UpdateWrapper<Question>().eq("id", questionVo.getQuestionId()));
        //设置答案对象
        StringBuffer multipleChoice = new StringBuffer();
        if (questionVo.getQuestionType() != 4) {//不为简答题
            Answer answer = new Answer();
            answer.setQuestionId(questionVo.getQuestionId());
            StringBuffer imgs = new StringBuffer();
            StringBuffer answers = new StringBuffer();
            for (int i = 0; i < questionVo.getAnswer().length; i++) {
                if (questionVo.getAnswer()[i].getImages() != null && questionVo.getAnswer()[i].getImages().length > 0) {//如果该选项有一张图片信息
                    imgs.append(questionVo.getAnswer()[i].getImages()[0]).append(",");
                }
                answers.append(questionVo.getAnswer()[i].getAnswer()).append(",");
                //设置对的选项的下标值
                if (questionVo.getQuestionType() == 2) {//多选
                    if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                        multipleChoice.append(i).append(",");
                    }
                } else {//单选和判断和填空 都是仅有一个答案
                    if (questionVo.getAnswer()[i].getIsTrue().equals("true")) {
                        answer.setTrueOption(i + "");
                        answer.setAnalysis(questionVo.getAnswer()[i].getAnalysis());
                    }
                }
            }
            if (questionVo.getQuestionType() == 2)
                answer.setTrueOption(multipleChoice.toString().substring(0, multipleChoice.toString().length() - 1));
            String handleImgs = imgs.toString();
            String handleAnswers = answers.toString();
            if (handleImgs.length() != 0) {
                handleImgs = handleImgs.substring(0, handleImgs.length() - 1);
            }
            if (handleAnswers.length() != 0) {
                handleAnswers = handleAnswers.substring(0, handleAnswers.length() - 1);
            }

            //设置答案的图片
            answer.setImages(handleImgs);
            //设置所有的选项
            answer.setAllOption(handleAnswers);
            answerService.update(answer, new UpdateWrapper<Answer>().eq("question_id", questionVo.getQuestionId()));
            redisUtil.del("questionVo:" + questionVo.getQuestionId());
        }
        return new CommonResult<>(200, "更新题目成功");
    }

    /**
     * @param file 图片文件
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadQuestionImage")
    public CommonResult<String> uploadQuestionImage(MultipartFile file) throws Exception {
        log.info("执行了===>TeacherController中的uploadQuestionImage方法");
        System.out.println(file.getOriginalFilename());
        String url = OSSUtil.picOSS(file);
        return new CommonResult<>(200, "上传成功", url);
    }

    /**
     * @param examQueryVo 考试信息查询vo对象
     * @return
     */
    @PostMapping("/getExamInfo")
    public CommonResult<List<Exam>> getExamInfo(@RequestBody ExamQueryVo examQueryVo,HttpServletRequest request) {
        log.info("执行了===>TeacherController中的getExamInfo方法");
        System.out.println(examQueryVo);
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            //参数一是当前页，参数二是每页个数
            IPage<Exam> examIPage = new Page<>(examQueryVo.getPageNo(), examQueryVo.getPageSize());
            //查询条件(可选)
            QueryWrapper<Exam> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            if (roleId.equals("2")) {
                String userName = tokenVo.getUsername();
                wrapper.eq("creator", userName);
            }else if(roleId.equals("1")){
                String userName = tokenVo.getUsername();
                QueryWrapper<UserClassRel> wrapperC = new QueryWrapper<>();
                wrapperC.eq("user_name",userName);
                List<UserClassRel> userClassRelList = userClassRelService.list(wrapperC);
                wrapper.and(w->{
                            userClassRelList.forEach(i->w.or().apply(!i.getClassId().isEmpty(), "FIND_IN_SET ('" + i.getClassId() + "',exam_class)"));
                            return w;
                        }
                );
            }
            if (examQueryVo.getExamType() != null) {
                wrapper.eq("type", examQueryVo.getExamType());
            }
            if (examQueryVo.getExamName() != null) {
                wrapper.like("exam_name", examQueryVo.getExamName());
            }
            if (examQueryVo.getStartTime() != null) {
                wrapper.and(wrapper2 -> wrapper2.between("start_time",
                        examQueryVo.getStartTime().substring(0, examQueryVo.getStartTime().indexOf(","))+ " 00:00:00",
                        examQueryVo.getStartTime().substring(examQueryVo.getStartTime().indexOf(",")+1)+ " 23:59:59").or().isNull("start_time"));
            }
            if (examQueryVo.getExamClass() != null) {
                wrapper.like("exam_class", examQueryVo.getExamClass());
            }
            wrapper.orderByDesc("start_time");
            IPage<Exam> page = examService.page(examIPage, wrapper);

            List<Exam> exams = page.getRecords();
            //将班级id转换为班级名称
            for(Exam exam:exams){
                String[] examClasses = exam.getExamClass().split(",");
                String classesName = new String();
                for(String examClass:examClasses){
                    Class examclass = classService.getById(examClass);
                    classesName += examclass.getClassName()+'('+ examclass.getClassId() +") ";
                }
                exam.setExamClass(classesName);
            }

            return new CommonResult<>(200, "查询考试信息成功", exams);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param addExamByQuestionVo 通过题目列表添加考试的vo对象
     * @return
     */
    @PostMapping("/addExamByQuestionList")
    public CommonResult<String> addExamByQuestionList(@RequestBody AddExamByQuestionVo addExamByQuestionVo,HttpServletRequest request) {
        log.info("执行了===>TeacherController中的addExamByQuestionList方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            Exam exam = new Exam();
            exam.setTotalScore(addExamByQuestionVo.getTotalScore());
            exam.setType(addExamByQuestionVo.getType());
            exam.setPassScore(addExamByQuestionVo.getPassScore());
            if (addExamByQuestionVo.getStartTime() != null) {
                exam.setStartTime(addExamByQuestionVo.getStartTime());
            }
            exam.setExamDesc(addExamByQuestionVo.getExamDesc());
            exam.setExamName(addExamByQuestionVo.getExamName());
            exam.setDuration(addExamByQuestionVo.getExamDuration());
            //设置密码如果有
            if (addExamByQuestionVo.getPassword() != null) {
                exam.setPassword(addExamByQuestionVo.getPassword());
            }else {
                exam.setPassword(null);
            }
            //设置考试班级
            exam.setExamClass(addExamByQuestionVo.getExamClass());
            exam.setStatus(addExamByQuestionVo.getStatus());
            //设置id
            List<Exam> examList = examService.list(new QueryWrapper<>());
            int id = 0;
            if (examList.size() != 0) {
                id = examList.get(examList.size() - 1).getExamId() + 1;
            }
            exam.setExamId(id);
            //设置创建人
            String userName = tokenVo.getUsername();
            exam.setCreator(userName);
            //设置考试的题目和分值信息
            ExamQuestion examQuestion = new ExamQuestion();
            examQuestion.setExamId(id);
            examQuestion.setScores(addExamByQuestionVo.getScores());
            examQuestion.setQuestionIds(addExamByQuestionVo.getQuestionIds());

            examService.save(exam);
            examQuestionService.save(examQuestion);
            return new CommonResult<>(200, "考试创建成功");
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param type 操作类型
     * @param ids  操作的考试id集合
     * @return
     */
    @GetMapping("/operationExam/{type}")
    public CommonResult<String> operationExam(@PathVariable("type") Integer type, String ids) {
        log.info("执行了===>TeacherController中的operationExam方法");
        String[] id = ids.split(",");
        //操作考试的信息表(type 1启用 2禁用 3删除)
        if (type == 1) {
            for (String s : id) {
                Exam exam = examService.getOne(new QueryWrapper<Exam>().eq("exam_id", Integer.parseInt(s)));
                exam.setStatus(1);
                examService.update(exam, new UpdateWrapper<Exam>().eq("exam_id", s));
            }
        } else if (type == 2) {
            for (String s : id) {
                Exam exam = examService.getOne(new QueryWrapper<Exam>().eq("exam_id", Integer.parseInt(s)));
                exam.setStatus(2);
                examService.update(exam, new UpdateWrapper<Exam>().eq("exam_id", s));
            }
        } else if (type == 3) {
            Map<String, Object> map = new HashMap<>();
            for (String s : id) {
                map.clear();
                map.put("exam_id", Integer.parseInt(s));
                examService.removeByMap(map);
                examQuestionService.removeByMap(map);
            }
        }
        return new CommonResult<>(200, "操作成功");
    }

    /**
     * @param addExamByQuestionVo
     * @return
     */
    @PostMapping("/updateExamInfo")
    public CommonResult<String> updateExamInfo(@RequestBody AddExamByQuestionVo addExamByQuestionVo) {
        log.info("执行了===>TeacherController中的updateExamInfo方法");
        Exam exam = new Exam();
        exam.setTotalScore(addExamByQuestionVo.getTotalScore());
        exam.setType(addExamByQuestionVo.getType());
        exam.setPassScore(addExamByQuestionVo.getPassScore());
        exam.setStartTime(addExamByQuestionVo.getStartTime());
        exam.setExamDesc(addExamByQuestionVo.getExamDesc());
        exam.setExamName(addExamByQuestionVo.getExamName());
        exam.setDuration(addExamByQuestionVo.getExamDuration());
        //设置密码如果有
        if (addExamByQuestionVo.getPassword() != null) {
            exam.setPassword(addExamByQuestionVo.getPassword());
        } else {
            exam.setPassword(null);
        }
        //设置考试班级
        exam.setExamClass(addExamByQuestionVo.getExamClass());
        exam.setStatus(addExamByQuestionVo.getStatus());
        exam.setExamId(addExamByQuestionVo.getExamId());
        //设置考试的题目和分值信息
        ExamQuestion examQuestion = new ExamQuestion();
        examQuestion.setExamId(addExamByQuestionVo.getExamId());
        examQuestion.setScores(addExamByQuestionVo.getScores());
        examQuestion.setQuestionIds(addExamByQuestionVo.getQuestionIds());

        examService.update(exam, new UpdateWrapper<Exam>().eq("exam_id", exam.getExamId()));
        examQuestionService.update(examQuestion, new UpdateWrapper<ExamQuestion>().eq("exam_id", exam.getExamId()));
        //移除缓存
        redisUtil.del("examInfo:" + exam.getExamId());
        return new CommonResult<>(200, "更新成功");
    }

    /**
     * @param examId 考试id
     * @return
     */
    @GetMapping("/getExamInfoById")
    public CommonResult<Object> getExamInfoById(@RequestParam Integer examId) {
        log.info("执行了===>TeacherController中的getExamInfoById方法");
        if (redisUtil.get("examInfo:" + examId) != null) {
            return new CommonResult<>(200, "查询成功", redisUtil.get("examInfo:" + examId));
        } else {
            //构造传递给前端的考试组合对象
            AddExamByQuestionVo addExamByQuestionVo = new AddExamByQuestionVo();
            Exam exam = examService.getOne(new QueryWrapper<Exam>().eq("exam_id", examId));
            addExamByQuestionVo.setExamDesc(exam.getExamDesc());
            addExamByQuestionVo.setExamDuration(exam.getDuration());
            addExamByQuestionVo.setExamId(examId);
            addExamByQuestionVo.setExamName(exam.getExamName());
            addExamByQuestionVo.setPassScore(exam.getPassScore());
            addExamByQuestionVo.setTotalScore(exam.getTotalScore());
            addExamByQuestionVo.setStartTime(exam.getStartTime());
            addExamByQuestionVo.setType(exam.getType());
            addExamByQuestionVo.setPassword(exam.getPassword());
            addExamByQuestionVo.setExamClass(exam.getExamClass());
            addExamByQuestionVo.setStatus(exam.getStatus());

            //考试中题目的对象
            ExamQuestion examQuestion = examQuestionService.getOne(new QueryWrapper<ExamQuestion>().eq("exam_id", examId));
            addExamByQuestionVo.setQuestionIds(examQuestion.getQuestionIds());
            addExamByQuestionVo.setScores(examQuestion.getScores());
            redisUtil.set("examInfo:" + examId, addExamByQuestionVo, 60 * 5 * new Random().nextInt(2));
            return new CommonResult<>(200, "查询成功", addExamByQuestionVo);
        }
    }

    /**
     * @param examRecord
     * @param request
     * @return
     */
    @PostMapping("/addExamRecord")
    public CommonResult<Integer> addExamRecord(@RequestBody ExamRecord examRecord, HttpServletRequest request) {
        log.info("执行了===>TeacherController中的addExamRecord方法");
        String token = request.getHeader("authorization");
        //当前用户对象的信息
        TokenVo tokenVo = TokenUtils.verifyToken(token);
        User user = userService.getOne(new QueryWrapper<User>().eq("username", tokenVo.getUsername()));
        //设置考试信息的字段
        examRecord.setUserId(user.getId());
        //设置id
        List<ExamRecord> examRecords = examRecordService.list(new QueryWrapper<>());
        int id = 1;
        if (examRecords.size() > 0) {
            id = examRecords.get(examRecords.size() - 1).getRecordId() + 1;
        }
        examRecord.setRecordId(id);

        //设置逻辑题目的分数
        //查询所有的题目答案信息
        List<Answer> answers = answerService.list(new QueryWrapper<Answer>().in("question_id", Arrays.asList(examRecord.getQuestionIds().split(","))));
        //查询考试的题目的分数
        HashMap<String, String> map = new HashMap<>();//key是题目的id  value是题目分值
        ExamQuestion examQuestion = examQuestionService.getOne(new QueryWrapper<ExamQuestion>().eq("exam_id", examRecord.getExamId()));
        //题目的id
        String[] ids = examQuestion.getQuestionIds().split(",");
        //题目在考试中对应的分数
        String[] scores = examQuestion.getScores().split(",");
        for (int i = 0; i < ids.length; i++) {
            map.put(ids[i], scores[i]);
        }
        //逻辑分数
        int logicScore = 0;
        //错题的id
        StringBuffer sf = new StringBuffer();
        //用户的答案
        String[] userAnswers = examRecord.getUserAnswers().split("-");
        for (int i = 0; i < examRecord.getQuestionIds().split(",").length; i++) {
            int index = SaltEncryption.getIndex(answers, Integer.parseInt(examRecord.getQuestionIds().split(",")[i]));
            if (index != -1) {
                Question question = questionService.getById(examRecord.getQuestionIds().split(",")[i]);
                String rightKey = new String();
                if(question.getQuType() ==5){   //填空题答案不是下标
                    rightKey = answers.get(index).getAllOption();
                }else{
                    rightKey = answers.get(index).getTrueOption();
                }
                if (Objects.equals(userAnswers[i], rightKey)) {
                    logicScore += Integer.parseInt(map.get(examRecord.getQuestionIds().split(",")[i]));
                } else {
                    sf.append(examRecord.getQuestionIds().split(",")[i]).append(",");
                }
            }
        }
        examRecord.setLogicScore(logicScore);
        if (sf.length() > 0) {//存在错的逻辑题
            examRecord.setErrorQuestionIds(sf.toString().substring(0, sf.toString().length() - 1));
        }

        System.out.println(examRecord);
        examRecord.setExamTime(new Date());
        examRecordService.save(examRecord);
        return new CommonResult<>(200, "考试记录保存成功", id);
    }

    /**
     * @param recordId 考试记录id
     * @return
     */
    @GetMapping("/getExamRecordById/{recordId}")
    public CommonResult<Object> getExamRecordById(@PathVariable Integer recordId) {
        log.info("执行了===>TeacherController中的getExamRecordById方法");
        if (redisUtil.get("examRecord:" + recordId) != null) {
            return new CommonResult<>(200, "考试信息查询成功", redisUtil.get("examRecord:" + recordId));
        } else {
            ExamRecord examRecord = examRecordService.getOne(new QueryWrapper<ExamRecord>().eq("record_id", recordId));
            redisUtil.set("examRecord:" + recordId, examRecord, 60 * 5 + new Random().nextInt(2) * 60);
            return new CommonResult<>(200, "考试信息查询成功", examRecord);
        }
    }

    /**
     * @param examId 考试id
     * @return
     */
    @GetMapping("/getExamQuestionByExamId/{examId}")
    public CommonResult<Object> getExamQuestionByExamId(@PathVariable Integer examId) {
        log.info("执行了===>TeacherController中的getExamQuestionByExamId方法");
        if (redisUtil.get("examQuestion:" + examId) != null) {
            return new CommonResult<>(200, "查询考试中题目和分值成功", redisUtil.get("examQuestion:" + examId));
        } else {
            ExamQuestion examQuestion = examQuestionService.getOne(new QueryWrapper<ExamQuestion>().eq("exam_id", examId));
            return new CommonResult<>(200, "查询考试中题目和分值成功", examQuestion);
        }
    }

    /**
     * @param examId   考试id
     * @param pageNo   页数
     * @param pageSize 页面大小
     * @return
     */
    @GetMapping("/getExamRecord")
    public CommonResult<Object> getExamRecord(@RequestParam(required = false) Integer examId,
                                              @RequestParam(required = false) Integer review,
                                              Integer pageNo, Integer pageSize , HttpServletRequest request) {
        log.info("执行了===>TeacherController中的getExamRecords方法");
        //参数一是当前页，参数二是每页个数
        IPage<ExamRecord> examRecordPage = new Page<>(pageNo, pageSize);
        CommonResult<List<Exam>> examList = this.allExamInfo(request);
        //查询条件(可选)
        QueryWrapper<ExamRecord> wrapper = new QueryWrapper<>();
        Integer code = examList.getCode();
        if(code == 200){
            List<Exam> exams = examList.getData();
            wrapper.and(w->{
                exams.forEach(i->w.or().eq("exam_id",i.getExamId()));
                        return w;
                    }
            );
        }
        if (examId != null) {
            wrapper.eq("exam_id", examId);
        }
        //是否批阅 1:已批阅
        if (review != null) {
            if(review == 1){
                wrapper.isNotNull("total_score");
            }else{
                wrapper.isNull("total_score");
            }
        }

        IPage<ExamRecord> page = examRecordService.page(examRecordPage, wrapper);

        List<ExamRecord> examRecords = page.getRecords();
        // 构造结果集
        Map<Object, Object> result = new HashMap<>();
        result.put("examRecords", examRecords);
        result.put("total", examRecordPage.getTotal());
        return new CommonResult<>(200, "success", result);
    }

    @GetMapping("/allExamInfo")
    public CommonResult<List<Exam>> allExamInfo(HttpServletRequest request) {
        log.info("执行了===>TeacherController中的allExamInfo方法");
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            QueryWrapper<Exam> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            if(!roleId.equals("3")){
                wrapper.eq("creator",tokenVo.getUsername());
            }
            List<Exam> exams = examService.list(wrapper);
            return new CommonResult<>(200, "所有考试信息获取成功", exams);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    /**
     * @param userId 用户id
     * @return
     */
    @GetMapping("/getUserById/{userId}")
    public CommonResult<Object> getUserById(@PathVariable Integer userId) {
        log.info("执行了===>TeacherController中的getUserById方法");
        if (redisUtil.get("user:" + userId) != null) {
            return new CommonResult<>(200, "用户信息查询成功", redisUtil.get("user:" + userId));
        } else {
            User user = userService.getOne(new QueryWrapper<User>().eq("id", userId));
            redisUtil.set("user:" + userId, user, 5 * 60 + new Random().nextInt(2) * 60);
            return new CommonResult<>(200, "用户信息查询成功", user);
        }
    }

    /**
     * @param totalScore   总成绩
     * @param examRecordId 考试记录id
     * @return
     */
    @GetMapping("/setObjectQuestionScore")
    public CommonResult<String> setObjectQuestionScore(Integer totalScore, Integer examRecordId) {
        ExamRecord examRecord = examRecordService.getOne(new QueryWrapper<ExamRecord>().eq("record_id", examRecordId));
        examRecord.setTotalScore(totalScore);
        boolean flag = examRecordService.update(examRecord, new UpdateWrapper<ExamRecord>().eq("record_id", examRecordId));
        return flag ? new CommonResult<>(200, "批阅成功") : new CommonResult<>(233, "批阅失败");
    }

    @GetMapping("/getExamPassRate")
    public CommonResult<List<String>> getExamPassRate(HttpServletRequest request) {
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            QueryWrapper<Exam> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            if(roleId.equals("2")){
                wrapper.eq("creator",tokenVo.getUsername());
            }
            List<Exam> exams = examService.list(wrapper);
            QueryWrapper<ExamRecord> wrapper1 = new QueryWrapper<>();
            wrapper1.isNotNull("total_score");
            wrapper1.and(w->{
                        exams.forEach(i->w.or().eq("exam_id",i.getExamId()));
                        return w;
                    }
            );
            List<ExamRecord> examRecords = examRecordService.list(wrapper1);
            //考试的名称
            String[] examNames = new String[exams.size()];
            //考试通过率
            double[] passRates = new double[exams.size()];

            double total = 0;
            double pass = 0;
            for (int i = 0; i < exams.size(); i++) {
                examNames[i] = exams.get(i).getExamName();
                total = 0;
                pass = 0;
                for (ExamRecord examRecord : examRecords) {
                    if (Objects.equals(examRecord.getExamId(), exams.get(i).getExamId())) {
                        total++;
                        if (examRecord.getTotalScore() >= exams.get(i).getPassScore()) pass++;
                    }
                }
                passRates[i] = pass / total;
            }
            for (int i = 0; i < passRates.length; i++) {
                if (Double.isNaN(passRates[i])) passRates[i] = 0;
            }
            List<String> list = new ArrayList<>();
            String res1 = Arrays.toString(examNames);
            String res2 = Arrays.toString(passRates);
            list.add(res1.substring(1, res1.length() - 1).replaceAll(" ", ""));
            list.add(res2.substring(1, res2.length() - 1).replaceAll(" ", ""));
            return new CommonResult<>(200, "考试通过率获取成功", list);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }

    @GetMapping("/getExamNumbers")
    public CommonResult<List<String>> getExamNumbers(HttpServletRequest request) {
        //工具类验证token是否有效 有效返回tokenVo对象,否则返回null
        TokenVo tokenVo = new CheckToken().checkToken(request, userService);
        System.out.println(tokenVo);
        //有效token
        if (tokenVo != null) {
            QueryWrapper<Exam> wrapper = new QueryWrapper<>();
            String roleId = tokenVo.getRoleId();
            if(roleId.equals("2")){
                wrapper.eq("creator",tokenVo.getUsername());
            }
            List<Exam> exams = examService.list(wrapper);
            QueryWrapper<ExamRecord> wrapper1 = new QueryWrapper<>();
            wrapper1.isNotNull("total_score");
            wrapper1.and(w->{
                        exams.forEach(i->w.or().eq("exam_id",i.getExamId()));
                        return w;
                    }
            );
            List<ExamRecord> examRecords = examRecordService.list(wrapper1);
            //考试的名称
            String[] examNames = new String[exams.size()];
            //考试的考试次数
            String[] examNumbers = new String[exams.size()];

            int total = 0;
            int cur = 0;
            for (int i = 0; i < exams.size(); i++) {
                examNames[i] = exams.get(i).getExamName();
                total = 0;
                cur = 0;
                for (ExamRecord examRecord : examRecords) {
                    total++;
                    if (Objects.equals(examRecord.getExamId(), exams.get(i).getExamId())) {
                        cur++;
                    }
                }
                examNumbers[i] = cur + "";
            }
            List<String> list = new ArrayList<>();
            String res1 = Arrays.toString(examNames);
            String res2 = Arrays.toString(examNumbers);
            list.add(res1.substring(1, res1.length() - 1).replaceAll(" ", ""));
            list.add(res2.substring(1, res2.length() - 1).replaceAll(" ", ""));
            return new CommonResult<>(200, "考试次数获取成功", list);
        } else {
            return new CommonResult<>(233, "认证信息有误,获取数据失败");
        }
    }
}
